package com.taptech.doufu.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.taptech.doufu.sdk.universalimageloader.core.ImageLoader;
import com.taptech.doufu.R;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.personalcenter.PersonalInfoService;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.DoufuUtils;
import com.taptech.doufu.services.GiftService;
import com.taptech.doufu.bean.MySpeakerInfo;
import com.taptech.doufu.util.TextUtil;
import com.taptech.doufu.util.at.AtClickListen;
import com.taptech.doufu.util.at.AtUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.WaitDialog;


public class MySpeakerActivity extends DiaobaoBaseActivity implements View.OnClickListener, HttpResponseListener {

    private static final int NO_DOUZI = 1;//豆币不足
    private static final int YELLOW_TEXT = 2;//敏感内容
    private static final int OTHER = 3;//其他错误

    private RelativeLayout mSpeakerVipInfo;
    private EditText mSpeakerEdit;
    private TextView mSpeakerBeanInfoCount;
    private TextView mSpeakerRuleInfo;
    private TextView mSpeakerBottomCount;
    private TextView mSpeakerVipExpiresDate;
    private TextView mSepakerAtIcon;
    private Button mSpeakerSendBtn;
    private RelativeLayout mMainRelativeLayout;
    private ImageView mSpeakerBigIcon;
    private RelativeLayout mBottomLayout;

    private WaitDialog dialog;
    private PopupWindow infoDialog;

    //发布喇叭请求参数
    private int bugles_id = 1;//喇叭类型
    private String message = " ";//喇叭内容
    private int direct_publish = 0;//强制发布



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_speaker_layout);
        initView();
        initEvent();
        initData();
        keyboradListen();

    }

    private void keyboradListen() {
        mMainRelativeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                Rect r = new Rect();
                mMainRelativeLayout.getWindowVisibleDisplayFrame(r);
                int screenHeight = mMainRelativeLayout.getRootView().getHeight();
                // r.bottom is the position above soft keypad or device button.
                // if keypad is shown, the r.bottom is smaller than that before.
                int keypadHeight = screenHeight - r.bottom;
                if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
                    mBottomLayout.setVisibility(View.GONE);
                }
                else {
                    mBottomLayout.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    private void showDialogByType(int type, String mainInfoStr){
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View dialogSpeaker = inflater.inflate(R.layout.dialog_my_speaker_info, null);
        TextView rightBtn = (TextView) dialogSpeaker.findViewById(R.id.dialog_speaker_right_btn);
        TextView leftBtn = (TextView) dialogSpeaker.findViewById(R.id.dialog_speaker_left_btn);
        TextView centerBtn = (TextView) dialogSpeaker.findViewById(R.id.dialog_speaker_center_btn);
        TextView buyVipBtn = (TextView) dialogSpeaker.findViewById(R.id.dialog_speaker_buy_vip);
        TextView mainInfo = (TextView) dialogSpeaker.findViewById(R.id.dialog_speaker_main_info);


        rightBtn.setOnClickListener(this);
        leftBtn.setOnClickListener(this);
        centerBtn.setOnClickListener(this);
        buyVipBtn.setOnClickListener(this);

        if (type == NO_DOUZI){
            rightBtn.setTag(NO_DOUZI);
        }else if (type == YELLOW_TEXT){
            rightBtn.setText("直接发布");
            rightBtn.setTag(YELLOW_TEXT);
            leftBtn.setText("返回修改");
            leftBtn.setTag(YELLOW_TEXT);
            buyVipBtn.setVisibility(View.GONE);
        }else if (type == OTHER) {
            rightBtn.setVisibility(View.GONE);
            leftBtn.setVisibility(View.GONE);
            centerBtn.setVisibility(View.VISIBLE);
            buyVipBtn.setVisibility(View.GONE);
        }
        mainInfo.setText(mainInfoStr);
        infoDialog = new PopupWindow(dialogSpeaker,ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        infoDialog.setOutsideTouchable(false);
        infoDialog.showAtLocation(mMainRelativeLayout, Gravity.CENTER ,0, 0);
        infoDialog.update();

    }





    private void initView() {
        mSpeakerVipInfo = (RelativeLayout) findViewById(R.id.my_speaker_vip_info);
        mSpeakerEdit = (EditText) findViewById(R.id.my_speaker_edit_text);
        mSpeakerBeanInfoCount = (TextView) findViewById(R.id.my_speaker_bean_info_count);
        mSpeakerRuleInfo = (TextView) findViewById(R.id.my_speaker_rule_info);
        mSpeakerBottomCount = (TextView) findViewById(R.id.my_speaker_bottom_count);
        mSpeakerVipExpiresDate = (TextView) findViewById(R.id.my_speaker_vip_expires_date);
        mSepakerAtIcon = (TextView) findViewById(R.id.my_speaker_at_icon);
        mSpeakerSendBtn = (Button) findViewById(R.id.my_speaker_send_btn);
        mMainRelativeLayout = (RelativeLayout) findViewById(R.id.main_relative_layout);
        mSpeakerBigIcon = (ImageView) findViewById(R.id.my_speaker_big_icon);
        mBottomLayout = (RelativeLayout) findViewById(R.id.my_speaker_vip_info);


    }
    private void initEvent() {
        mSpeakerVipInfo.setOnClickListener(this);
        mSpeakerSendBtn.setOnClickListener(this);
        AtClickListen atClickListen = new AtClickListen(this, mSpeakerEdit, mSepakerAtIcon);

    }
    private void initData() {
        if (dialog == null) {
            dialog = new WaitDialog(this, R.style.updateDialog);
        }
        dialog.show();
        if (AccountService.getInstance().getUserUid() != null && AccountService.getInstance().isLogin()) {
            PersonalInfoService.getInstance().getMySpeakerInfo(this);//请求页面基本信息
        }else {
            AccountService.getInstance().jumpToLogin();
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_speaker_vip_info://开通会员
                DoufuUtils.startVipActivity(MySpeakerActivity.this);
                break;
            case R.id.my_speaker_send_btn://发送小喇叭
                sendMySpeaker();
                break;
            case R.id.dialog_speaker_buy_vip:
                DoufuUtils.startVipActivity(MySpeakerActivity.this);
                break;
            case R.id.dialog_speaker_left_btn:
                infoDialog.dismiss();
                break;
            case R.id.dialog_speaker_right_btn:
                if ((int)v.getTag() == YELLOW_TEXT) {
                    direct_publish = 1;
                    sendMySpeaker();
                    infoDialog.dismiss();
                }else {
                    startBeanActivity();
                }
                break;
            case R.id.dialog_speaker_center_btn:
                infoDialog.dismiss();
                break;
            default:
                break;
        }
    }

    private void sendMySpeaker() {
        dialog.show();
        if (AccountService.getInstance().getUserUid() != null){
            message = mSpeakerEdit.getText().toString();
            PersonalInfoService.sendSpeakerInfo(this, message, String.valueOf(direct_publish), String.valueOf(bugles_id));
        }
    }

    @Override
    protected void onRestart() {
        initData();
        super.onRestart();
    }

    /**
     * 跳转到豆币页面
     */
    private void startBeanActivity() {
        GiftService.enterPayWebActivity(MySpeakerActivity.this);
    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        try {
            if (response == null){
                UIUtil.toastMessage(this, Constant.loadingFail);
                return;
            }

            switch (handleType){
                case PersonalInfoService.HANDLE_TYPE_GET_SPEAKER_INFO://页面基本信息
                    if (response.getStatus() == 0) {
                        initPageDate(response);
                    }else {
                        UIUtil.toastMessage(this, "网络异常，请检查网络后再试");
                    }
                    break;
                case PersonalInfoService.HANDLE_LOAD_MYSPEAKER_SEND://发送小喇叭
                    if (response.getStatus() == 0) {//发送成功
                        initData();
                        mSpeakerEdit.setText("");
                        dialog.dismiss();
                        Toast.makeText(MySpeakerActivity.this,"发送成功", Toast.LENGTH_LONG).show();
                    }else if (response.getStatus() == 32){//豆币不足
                        showDialogByType(NO_DOUZI,response.getUser_msg());
                    }else if (response.getStatus() == 514) {//内容敏感
                        showDialogByType(YELLOW_TEXT,response.getUser_msg());
                    }else {//其他错误
                        showDialogByType(OTHER,response.getUser_msg());
                    }
                    break;

            }
        } catch (Exception e) {
            e.printStackTrace();
            UIUtil.toastMessage(this, "网络异常，请检查网络后再试");
        }
        dialog.dismiss();
    }

    /**
     * 初始化页面数据的加载
     * @param response
     */
    private void initPageDate(HttpResponseObject response) {
        try {
            MySpeakerInfo mySpeakerInfo = MySpeakerInfo.getMySpeakerInfo(response.getData().toString());
            mSpeakerBeanInfoCount.setText(String.valueOf(mySpeakerInfo.getBugles().get(0).getCoins()));
            mSpeakerRuleInfo.setText(mySpeakerInfo.getBugles().get(0).getDesc());
            mSpeakerBottomCount.setText(mySpeakerInfo.getUser().getTip1());
            if (!TextUtil.isEmpty(mySpeakerInfo.getUser().getTip2())){
                mSpeakerVipExpiresDate.setVisibility(View.VISIBLE);
                mSpeakerVipExpiresDate.setText(mySpeakerInfo.getUser().getTip2());
            }else {
                mSpeakerVipExpiresDate.setVisibility(View.GONE);
            }
            ImageLoader imageLoader = ImageLoader.getInstance();
            imageLoader.displayImage(mySpeakerInfo.getBugles().get(0).getImage(),mSpeakerBigIcon);
            bugles_id = mySpeakerInfo.getBugles().get(0).getId();
            mSpeakerEdit.setHint("编辑小喇叭" + mySpeakerInfo.getBugles().get(0).getPlace_holder());
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constant.AT_RESULI){
            if (data != null){
                String textString = "";
                String user_nikename = data.getStringExtra("user_nikename");
                if (user_nikename != null){
                    if (requestCode == Constant.AT_CLICK){
                        textString = mSpeakerEdit.getText().toString() + "@" + user_nikename + " ";
                    } else if (requestCode == Constant.AT_WRITE){
                        textString = mSpeakerEdit.getText().toString() + user_nikename + " ";
                    }
                    new AtUtil(mSpeakerEdit, textString, Constant.AT_WRITE);
                }
            }
        }
    }

}
